package com.wolf.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wolf.common.utils.R;
import com.wolf.gulimall.cart.feign.ProductFeignService;
import com.wolf.gulimall.cart.interceptor.CartInterceptor;
import com.wolf.gulimall.cart.service.CartService;
import com.wolf.gulimall.cart.to.UserInfoTo;
import com.wolf.gulimall.cart.vo.CartItemVo;
import com.wolf.gulimall.cart.vo.CartVo;
import com.wolf.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Null;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 购物车service
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    /**
     * 添加商品商品到购物车
     *
     * @param skuId 商品ID
     * @param num   添加商品数量
     * @return 购物项内容
     */
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String result = (String) cartOps.get(skuId.toString());

        if (StringUtils.isEmpty(result)) {
            //先判断购物车中是否有该商品,没有添加该商品信息
            //查询当前商品的信息
            CartItemVo cartItemVo = new CartItemVo();
            CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
                SkuInfoVo skuInfo = new SkuInfoVo();
                R info = productFeignService.getInfo(skuId);
                if (info.getCode() == 0) {
                    skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                }
                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setSkuId(skuId);
                cartItemVo.setPrice(skuInfo.getPrice());
            }, executor);

            //查询sku组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);
            //等待异步编排任务都执行完成之后,在进行后续操作
            CompletableFuture.allOf(completableFuture, getSkuSaleAttrValues).get();
            String s = JSON.toJSONString(cartItemVo);
            //将封装好的购物项数据存储到redis中
            cartOps.put(skuId.toString(), s);
            return cartItemVo;
        } else {
            //如果购物车中有该商品,改变购物车中该商品的数量
            CartItemVo cartItemVo = JSON.parseObject(result, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }
    }


    /**
     * 根据商品ID查询购物车信息
     *
     * @param skuId 商品ID
     * @return 购物车信息
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(res, CartItemVo.class);
    }

    /**
     * 获取购物车信息
     *
     * @return 购物车信息
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        //获取当前用户信息,从本地线程变量中获取
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //已登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
            //已登录的用户购物车信息,先判断临时购物车中是否存在商品
            String cartKeys = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> cartItemVos = getCartItemVos(cartKeys);
            if (cartItemVos != null) {
                //合并临时购物车的数据到用户的购物车中
                for (CartItemVo cartItemVo : cartItemVos) {
                    addToCart(cartItemVo.getSkuId(), cartItemVo.getCount());
                }
                //清除临时购物车数据
                clearCart(cartKeys);
            }
            //登录后的购物车数据(包含了临时购物车中的数据)
            List<CartItemVo> cartItemVosList = getCartItemVos(cartKey);
            cartVo.setItems(cartItemVosList);
        } else {
            //没有登录,临时购物车
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> cartItemVos = getCartItemVos(cartKey);
            cartVo.setItems(cartItemVos);
        }

        return cartVo;
    }


    /**
     * 获取操作购物车对象
     *
     * @return 操作购物车对象
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //获取当前用户信息,从本地线程变量中获取
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //判断用户是否登录
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //用户以登录
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            //用户没有登录,使用临时购物车
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }

    /**
     * 根据购物车的键获取购物车信息
     *
     * @param cartKey 购物车的键
     * @return 购物车信息
     */
    private List<CartItemVo> getCartItemVos(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps
                = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            return values.stream().map(value -> {
                String res = (String) value;
                return JSON.parseObject(res, CartItemVo.class);
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 清除购物车
     *
     * @param cartKey 购物车键
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    /**
     * 修改购物车中商品被选中状态
     *
     * @param skuId   商品ID
     * @param checked 被选中状态
     */
    @Override
    public void checkItem(Long skuId, Integer checked) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(checked == 1);
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    /**
     * 修改购物车中商品数量
     *
     * @param skuId 商品ID
     * @param num   商品数量
     */
    @Override
    public void checkItemCount(Long skuId, Integer num) {
        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), redisValue);
    }


    /**
     * 删除购物车商品
     *
     * @param skuId 商品ID
     */
    @Override
    public void deleteIdCartInfo(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }


    /**
     * 查询用户购物车详情信息
     *
     * @return 购物车详情信息
     */
    @Override
    public List<CartItemVo> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            List<CartItemVo> cartItemVos = getCartItemVos(CART_PREFIX + userInfoTo.getUserId());
            log.info("cartItemVos:{}",cartItemVos);
            if (cartItemVos != null && cartItemVos.size() > 0) {
                return cartItemVos.stream().filter(CartItemVo::getCheck)
                        //更新购物车中商品的最新价格
                        .peek(item -> {
                            R price = productFeignService.getPrice(item.getSkuId());
                            if (price.getCode() == 0) {
                                String data = (String) price.get("data");
                                item.setPrice(new BigDecimal(data));
                            }
                        })
                        .collect(Collectors.toList());
            } else {
                return null;
            }
        } else {
            //用户没有登录返回空
            return null;
        }
    }


}
